import type { SetupContext } from 'vue'
import { getCurrentInstance, nextTick } from 'vue'
import { mergeColumnMethod } from '@v-model/shared--utils'
import { VTableProps, VtableEmits } from './vtableProps'
import type { Ref } from 'vue'
import { VTableRef } from './table'
import { useElementEvent } from './use-elevent'

// 设置关联医嘱

/**
 *  当前行是否选中
 * @param selection 选中的数据源
 * @param row 当前点击的行
 * @returns
 **/
export const hasSelected = (selection: any, row: any) => !(selection.indexOf(row) === -1)

// 设置表格指定字段聚焦
export const setFoucskey = (row: any, key: string) => {
  if (!key) return
  let foucskey = key + 'focus'
  row[foucskey] = true
  nextTick(() => {
    delete row[foucskey]
  })
}

/**
 * 单元格合并
 * @param props 父组件传入的参数列表
 * @param targetRef table表格实例
 * @param emits 向外暴露的方法
 * @returns
 */
export const rowspan = (props: VTableProps, targetRef: VTableRef) => {
  const instance = getCurrentInstance()!
  const emits = instance.emit as SetupContext<VtableEmits>['emit']

  const { toggleRowSelection, getSelectionRows, setCurrentRow, toggleAllSelection, setScrollTop } = useElementEvent(
    props,
    targetRef
  )

  // 单元格合并
  function spanMethod({ row, column, rowIndex, columnIndex }: { row: any; column: any; rowIndex: number; columnIndex: number }) {
    const item = props.columns.filter((it: any) => it.mspan).map((it: any) => it.prop) as any
    const table = props.data as any
    return mergeColumnMethod(table, item, { row, column, rowIndex, columnIndex })
  }

  const isGather = (val: any, key: string) => {
    let items = props.data.filter((item: any) => item[key] === val)
    return items.length > 1
  }

  // 设置关联医嘱
  const selectRow = (selection: any, row: any) => {
    if (props.sameTick && !props.rowkey) console.warn('设置同组勾选时，必须要设置 rowkey 字段')
    // 当为同组的勾选  sameTick
    if (props.rowkey && props.sameTick) {
      /**
       * unitTick 启用，只能勾选一组， 清空已勾选的数据，再勾选
       * */
      if (props.unitTick) targetRef.value.clearSelection()

      // 先设置当前选中行数据的勾选或者取消勾选
      targetRef.value.toggleRowSelection(row, hasSelected(selection, row))

      // 将数据源循环遍历，设置同组的 勾选或者取消
      props.data.forEach((it: any) => {
        if (row[props.rowkey] && it[props.rowkey] === row[props.rowkey]) {
          targetRef.value.toggleRowSelection(it, hasSelected(selection, row))
        }
      })
    }
    const handlerSelections = getSelectionRows()
    emits('select', handlerSelections, row)
  }

  // 返回所有选中数据
  const handleSelectionChange = (selection: any) => {
    // 处理关联时异步只选中一个的问题
    const handlerSelections = getSelectionRows()
    emits('selection-change', handlerSelections)
  }

  // 勾选选中所有按钮
  const selectAll = (selection: any) => {
    emits('select-all', selection)
  }

  return {
    spanMethod,
    isGather,
    selectRow,
    handleSelectionChange,
    selectAll,
    toggleRowSelection,
    getSelectionRows,
    setCurrentRow,
    toggleAllSelection,
    setScrollTop,
  }
}
